#!/bin/bash
apt update && apt install -y python3 unzip make ninja-build pkg-config tree tar curl

# 下载或更新
cloneOrPull() {
    GIT_URL=$1
    TARGET_DIR=$2
    if [ "$TARGET_DIR" == "" ]; then
        var1=${GIT_URL##*/}
        TARGET_DIR=${var1%.*}
    fi
    echo "GIT_URL=$GIT_URL"
    echo "TARGET_DIR=$TARGET_DIR"
    if [ ! -d "$TARGET_DIR/.git" ] || [ "$(git -C $TARGET_DIR status -s)" != "" ]; then
        rm -rf $TARGET_DIR
        mkdir -p $TARGET_DIR
        git clone $GIT_URL $TARGET_DIR
    else
        git -C $TARGET_DIR pull
    fi
}

# 下载相关依赖
cloneOrPull https://gitee.com/getmoon/depot_tools.git
cloneOrPull https://gitee.com/getmoon/flutter_engine_src.git
cloneOrPull https://gitee.com/getmoon/flutter_engine_third_party.git
cloneOrPull https://gitee.com/getmoon/flutter_git_bak.git
cloneOrPull https://gitee.com/getmoon/flutter-vpython.git
cloneOrPull https://gitee.com/getmoon/flutter_engine_patch.git
cloneOrPull https://gitee.com/getmoon/flutter_env.git

# 文件夹移动
echo "--> Start move files"
rm -rf ndk
rm -rf src
cp -ar flutter_engine_src/. src/
cp -ar third_party/flutter/engine/. src/flutter/
cp -ar flutter_engine_third_party/. src/third_party/

rm -rf .vpython_cipd_cache
rm -rf .vpython-root
cp -ar flutter-vpython/.vpython_cipd_cache/. .vpython_cipd_cache/
cp -ar flutter-vpython/.vpython-root/. .vpython-root/

echo "--> Start unzip files"
unzip -q flutter_git_bak/dart.git.zip -d src/third_party/dart
unzip -q flutter_git_bak/angle.git.zip -d src/third_party/angle
unzip -q flutter_git_bak/skia.git.zip -d src/third_party/skia
unzip -q flutter_git_bak/zlib.git.zip -d src/third_party/zlib
unzip -q flutter_git_bak/libcxx.git.zip -d src/third_party/libcxx
unzip -q flutter_git_bak/spirv-headers.git.zip -d src/third_party/vulkan-deps/spirv-headers/src

#创建npmrc文件
rm -f ~/.npmrc
echo -e "registry=https://repo.huaweicloud.com/repository/npm/\n@ohos:registry=https://repo.harmonyos.com/npm/\nlockfile=false" > ~/.npmrc
rm -rf ~/.ohpm
mkdir ~/.ohpm
touch ~/.ohpm/.ohpmrc
echo -e "registry=https://ohpm.openharmony.cn/ohpm/" > ~/.ohpm/.ohpmrc
# 删除hvigor缓存
rm -rf ~/.hvigor

rm -rf flutter_engine_patch/.git && chmod 777 pre_script/copy_files.sh && pre_script/copy_files.sh flutter_engine_patch/ src/flutter/

python3 src/flutter/attachment/scripts/ohos_setup_pre.py && ./setup.sh
echo "--> Finish engine_pre.sh ."